<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useTokenStore } from '@/store/token.js'
import { Plus } from "@element-plus/icons-vue"; // 注意：如果Plus图标未在此上下文中使用，此行可能是多余的
import {
  selectUserService,
  updateUserInfoService,
  updatePicService,
  deleteUserService,
  updatePwdOne
} from "@/api/user/userInfo.js";

import { useUserInfoStore } from '@/store/user.js'
//路由
import router from "@/router";

//token
const tokenStore = useTokenStore()

const userInfoStore = useUserInfoStore()
// 移除类型注解，并确保函数签名与原始意图一致
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
};
const imageUrl = ref();
//用户信息数据模型
const userInfo = ref({});
//查到当前登录用户
const getUserInfo = async () => {
  let result = await selectUserService();
  userInfo.value = result.data;
  imageUrl.value = userInfo.value.userAvatar
};
getUserInfo();

//修改用户信息
const updateUserInfo = async () => {
  let result = await updateUserInfoService(userInfo.value);
  ElMessage.success(result.message ? result.message : '修改成功')
  //更新pinia中的数据
  userInfoStore.userInfo.nickName = userInfo.value.nickName
};
// 控制密码弹出框
const dialogVisible = ref(false);
//打开弹出框
const openModal = () => {
  //密码模型清空
  pwdModel.value = { old_pwd: "", new_pwd: "", re_pwd: "" };
  dialogVisible.value = true;
};
//数据校验
const rules = {
  nickName: [
    { required: true, message: "请输入用户昵称", trigger: "blur" },
    { min: 2, max: 16, message: "昵称必须为2~10位的非空字符", trigger: "blur" },
  ],
  userEmail: [
    { required: true, message: "请输入用户邮箱", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: "blur" },
  ],
};
//修改资料校验
const uploadRefo = ref();
//图片绑定
const uploadRef = ref();
//密码表单校验
const formRef = ref(null);
//个人信息校验
const updateUserInfoOne = (state) => {
  uploadRefo.value.validate((valid) => {
    if (valid) {
      updateUserInfo();
    } else {
      return false;
    }
  });
};

//修改密码模型数据
const pwdModel = ref({
  old_pwd: "",
  new_pwd: "",
  re_pwd: "",
});
//确认密码校验
const rePasswordValid = (rule, value, callback) => {
  if (value == null || value === "") {
    return callback(new Error("请再次确认密码"));
  } else if (pwdModel.value.new_pwd !== value) {
    return callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};
const rulesPwd = {
  old_pwd: [
    { required: true, message: "请输入当前密码", trigger: "blur" },
    { min: 5, max: 16, message: "密码长度必须为5~16位", trigger: "blur" },
  ],
  new_pwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 5, max: 16, message: "密码长度必须为5~16位", trigger: "blur" },
  ],
  re_pwd: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    { validator: rePasswordValid, trigger: "blur" },
  ],
};
//提交进行数据校验，校验通过后才执行调用修改密码的方法
const updatePwd = (state) => {
  formRef.value.validate((valid) => {
    if (valid) {
      submitUpdatePwd();
    } else {
      return false;
    }
  });
};

//表单校验通过，调用修改密码的方法
const submitUpdatePwd = async () => {
  let result = await updatePwdOne(pwdModel.value);
  console.log(result)
  if (result.code == 200) {
    ElMessage.success(result.message ? result.message : '修改成功')
    router.push("/Login")
  }
}
//图片上传成功的回调
const uploadSuccess = (result) => {
  //回显图片
  imageUrl.value = result.data
}
//修改头像
const updatePicOne = async () => {
  let result = await updatePicService(imageUrl.value)
  if (result.code == 200) {
    //更新pinia中的头像
    userInfoStore.userInfo.userAvatar = imageUrl.value
    ElMessage.success('修改成功')

  } else {
    ElMessage.error('修改失败')
  }
}
</script>

<template>
  <div class="userInfo">
    <div class="left">
      <router-link to="/user/UserInfo">
        <div class="category1">个人资料</div>
      </router-link>
      <!-- <router-link to="/user/UserSafe">
        <div class="category2">安全设置</div>
      </router-link> -->
    </div>
    <div class="right-1">
      <div class="formInfo">
        <div class="updatePic">
          <el-upload ref="uploadRef" class="avatar-uploader" action="/api/user/upload" :show-file-list="false"
            :on-success="uploadSuccess" :headers="{ 'Authorization': tokenStore.token }" :value="imageUrl">
            <img v-if="imageUrl" :src="imageUrl" class="avatar-uploader" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
          <el-button type="primary" @click="uploadRef.$el.querySelector('input').click()">选择头像</el-button>
          <el-button type="primary" :icon="Upload" size="large" @click="updatePicOne" style="height: 30px;">
            上传头像
          </el-button>
        </div>
        <div class="info">
          <el-form :model="userInfo" :rules="rules" ref="uploadRefo">
            <p>用户名称</p>
            <el-form-item prop="nickName">
              <el-input v-model="userInfo.nickName" prop="name" style="width: 600px" maxlength="20" show-word-limit
                type="text" />
            </el-form-item>
            <p>性别</p>
            <el-form-item prop="userSex">
              <el-radio-group v-model="userInfo.userSex">
                <el-radio :value="'2'">暂时保密</el-radio>
                <el-radio :value="'0'">男</el-radio>
                <el-radio :value="'1'">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <p>邮箱地址</p>
            <el-form-item prop="userEmail">
              <el-input v-model="userInfo.userEmail" style="width: 600px" placeholder="请输入邮箱地址" />
            </el-form-item>
            <p>身份证号</p>
            <el-form-item prop="">
              <el-input disabled v-model="userInfo.userCard" style="width: 600px" placeholder="请输入身份证号" />
            </el-form-item>
            <p>账号类型</p>
            <el-form-item prop="role">
              <el-input :value="userInfo.userType == 1 ? '老师' : (userInfo.userType == 2 ? '学生' : '管理员')" disabled
                style="width: 600px" />
            </el-form-item>
            <p>我的账号（手机号）</p>
            <el-form-item prop="username">
              <el-input disabled style="width: 600px" v-model="userInfo.userPhone" />
            </el-form-item>
            <el-form-item style="margin-top: 20px">
              <el-button type="primary" @click="updateUserInfoOne">
                确认修改
              </el-button>
              <button @click="openModal" type="button" style="
                  width: 88px;
                  height: 32px;
                  background: #409eff;
                  color: #ffffff;
                  margin-left: 30px;
                  border: none; 
                  border-radius: 5px;
                ">
                修改密码
              </button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="prompt">
        <p class="promptH">个人资料</p>
        <p class="promptC">请填写真实信息，以便为您提供更多服务</p>
      </div>
    </div>
    <!-- 弹出框 -->
    <el-dialog v-model="dialogVisible" style="width: 500px">
      <el-form ref="formRef" :model="pwdModel" :rules="rulesPwd" label-width="80px">
        <el-form-item prop="old_pwd">
          原密码：<el-input style="width: 300px" v-model="pwdModel.old_pwd" type="password" />
        </el-form-item>
        <el-form-item prop="new_pwd">
          新密码：<el-input style="width: 300px" v-model="pwdModel.new_pwd" type="password" />
        </el-form-item>
        <el-form-item prop="re_pwd" style="margin-left: -30px">
          确认新密码：<el-input style="width: 300px" v-model="pwdModel.re_pwd" type="password" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePwd"> 提交修改 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
body {
  background-color: rgba(243, 242, 242, 0.486);
}

.el-form-item__content {
  margin-top: 20px;
}

.updatePic {
  margin-top: 20px;
  width: 310px;
  height: 110px;
  align-items: center;
  display: flex;
}

.userInfo {
  display: flex;

  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
  }

  .modal-content {
    background-color: #fefefe;
    padding: 20px;
    border: 1px solid #888;
    width: 300px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  .left {
    background: white;
    width: 280px;
    height: 70px;
    // font-size: 12px;
    margin-left: 180px;
    margin-top: 30px;

    a {
      color: black;
      text-decoration: none;
    }

    div {
      width: 210px;
      height: 45px;
      margin: 10px 0;
      line-height: 45px;
      text-indent: 2em;
    }

    div:hover {
      color: rgb(64, 158, 255);
      cursor: pointer;
      border-left: rgb(64, 158, 255) solid 2px;
    }
  }

  .right-1 {
    width: 1100px;
    height: 800px;
    margin-left: 15px;
    margin-top: 30px;
    background-color: white;
    display: flex;
    flex-direction: row;

    .formInfo {
      width: 800px;
      height: 800px;
      margin-left: 50px;

      .updatePic {
        img {
          width: 70px;
          height: 70px;
          border-radius: 200px;
          border: solid 1px black;
          vertical-align: middle;
        }

        .el-button {
          margin-left: 25px;
          vertical-align: middle;
        }
      }

      .info {
        margin-top: 35px;
        // transform: scale(0.8);
      }
    }

    .prompt {
      padding: 50px 40px;
      width: 344px;
      height: 800px;
      background: rgba(197, 196, 196, 0.075);

      .promptC {
        margin-top: 20px;
        font-size: 14px;
        color: rgb(126, 125, 125);
        // text-align: center;
      }

      .promptH {
        margin-top: 20px;
        // text-align: center;
      }
    }
  }
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  width: 70px;
  height: 70px;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
